import { HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Brand } from 'src/app/model/brand';
import { BrandApiService } from '../../../api/brand-api.service';
import { TableCheckService } from 'src/app/utils/table-check.service';


@Component({
  selector: 'app-brand',
  templateUrl: './brand.component.html',
  styleUrls: ['./brand.component.less', '../../../styles/container.css'],
  providers: [TableCheckService]
})
export class BrandComponent implements OnInit {
  searchForm: FormGroup;
  brandList: Brand[];
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  batchOperate: string;
  tableLoading = false;
  // factoryStatusLoading: boolean;
  operateOptions = [
    {
      label: '显示品牌',
      value: 'showBrand'
    },
    {
      label: '隐藏品牌',
      value: 'hideBrand'
    }
  ];
  showStatusLoadingStatus: Map<number, boolean> = new Map();
  factoryStatusLoadingStatus: Map<number, boolean> = new Map();

  constructor(
    private fb: FormBuilder,
    private brandApi: BrandApiService,
    private message: NzMessageService,
    private modal: NzModalService,
    private router: Router,
    public tableCheck: TableCheckService,
  ) { }

  ngOnInit(): void {
    this.searchForm = this.fb.group({ keyword: [''] });
    this.getBrandListFromServer();
  }

  handleAdd(): void {
    this.router.navigateByUrl('pms/addBrand');
  }

  onSubmit(): void {
    this.getBrandListFromServer();
  }

  handleBatchOpterate(): void {
    if (!this.tableCheck.setOfCheckedId || this.tableCheck.setOfCheckedId.size < 1) {
      this.message.error('请选择要操作的商品', { nzDuration: 1000, nzPauseOnHover: true });
      return;
    }
    if (!this.batchOperate) {
      this.message.error('请选择操作', { nzDuration: 1000 });
      return;
    }
    this.modal.confirm({
      nzTitle: '是否进行批量操作？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOnOk: this.applyatBchOperater,
      nzCancelText: '取消',
      nzMaskClosable: true,
    });
  }


  handleDelete(id: number): void {
    this.modal.confirm({
      nzTitle: '确定删除此商品？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        this.brandApi.delete([id]).subscribe(
          respon => {
            this.message.success('删除成功');
            this.getBrandListFromServer();
          },
          err => {
            this.message.error('删除错误');
          }
        );
      },
      nzCancelText: '取消',
      nzMaskClosable: true,
    });
  }

  handleUpdate(id: number): void {
    const url = this.router.parseUrl('/pms/updateBrand');
    url.queryParams = { id };
    this.router.navigateByUrl(url);
  }


  handlePageIndexChange(): void {
    this.getBrandListFromServer();
  }

  handlePageSizeChange(): void {
    this.getBrandListFromServer();
  }

  handleFactoryStatusClick(id: number): any {
    const currentStatu = this.brandList.find(brand => brand.id === id).factoryStatus;
    const modifyStatu = currentStatu ? 0 : 1;
    this.updateFactoryStatu([id], modifyStatu);
  }



  handleShowStatusClick(id: number): any {
    this.showStatusLoadingStatus.set(id, true);
    const data = new FormData();
    const currentStatu = this.brandList.find(brand => brand.id === id).showStatus;
    const modifyStatu = currentStatu ? 0 : 1;
    data.append('ids', id.toString());
    data.append('showStatus', modifyStatu.toString());
    this.brandApi.updateShowStatus(data).subscribe(
      response => {
        this.message.success('修改成功');
        this.brandList.find(brand => brand.id === id).showStatus = modifyStatu;
        this.showStatusLoadingStatus.set(id, false);
      },
      err => {
        this.message.error('修改错误');
        this.showStatusLoadingStatus.set(id, false);
        console.error(err);
      }
    );
  }

  private getBrandListFromServer(): any {
    this.tableLoading = true;
    let params = new HttpParams({
      fromObject: {
        pageNum: this.pageIndex.toString(),
        pageSize: this.pageSize.toString()
      }
    });
    const keywordValue = this.searchForm.get('keyword');
    if (keywordValue.value) {
      params = params.append('keyword', keywordValue.value);
    }


    this.brandApi.list(params).subscribe(
      respone => {
        this.tableCheck.setOfCheckedId.clear();
        this.tableCheck.idList = [];
        this.total = respone.total;
        this.brandList = respone.list;
        this.tableLoading = false;
        for (const brandInfo of respone.list) {
          this.showStatusLoadingStatus.set(brandInfo.id, false);
          this.factoryStatusLoadingStatus.set(brandInfo.id, false);
          this.tableCheck.idList.push(brandInfo.id);
        }
      },
      err => {
        console.error(err);
        this.tableLoading = false;
      }
    );
  }

  private applyatBchOperater = () => {
    switch (this.batchOperate) {
      case this.operateOptions[0].value:
        this.updateFactoryStatu(Array.from(this.tableCheck.setOfCheckedId), 1);
        break;
      case this.operateOptions[1].value:
        this.updateFactoryStatu(Array.from(this.tableCheck.setOfCheckedId), 0);
        break;

    }
  }


  private updateFactoryStatu(brandIds: Array<number>, factoryStatus: number): void {
    for (const id of brandIds) {
      this.factoryStatusLoadingStatus.set(id, true);
    }
    const data = new FormData();
    data.append('ids', brandIds.toString());
    data.append('factoryStatus', factoryStatus.toString());
    this.brandApi.updataFactoryStatus(data).subscribe(
      response => {
        this.message.success('修改成功');
        for (const id of brandIds) {
          this.brandList.find(brand => brand.id === id).factoryStatus = factoryStatus;
          this.factoryStatusLoadingStatus.set(id, false);
        }

      },
      err => {
        this.message.error('修改错误');
        for (const id of brandIds) {
          this.brandList.find(brand => brand.id === id).factoryStatus = factoryStatus;
          this.factoryStatusLoadingStatus.set(id, false);
        }
        console.error(err);
      }
    );
  }
}
